package com.dycn.service;

import com.dycn.dao.ActivitysMapper;
import com.dycn.dao.CyUserMapper;
import com.dycn.dao.RedisDao;
import com.dycn.dao.TasksActivitiesMapper;
import com.dycn.model.*;
import com.dycn.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TaskService {
    @Autowired
    TasksActivitiesMapper tasksActivitiesMapper;
     @Autowired
    RedisDao redisDao;

     @Autowired
    CyUserMapper cyUserMapper;

     @Autowired
    ActivitysMapper activitysMapper;
//ismart999.com
//
//ismart999.com
//
//ismart999.com
    public List<TasksActivitiesVo> list(CyUser cyUser,String code,String type,Integer activityId, HttpServletResponse httpServletResponse){
         if(cyUser==null){
             cyUser=getCyUser(code,httpServletResponse);
         }
        List<TasksActivitiesVo> tasksActivitiesList=tasksActivitiesMapper.list(cyUser.getOpenid(),type,activityId);
        //Collections.sort(tasksActivitiesList,new TaskCompare());
        for (int i=0;i<tasksActivitiesList.size();i++){
            TasksActivitiesVo tasksActivities=tasksActivitiesList.get(i);
            tasksActivities.setOrder(i+1);
            tasksActivities.setCode(getCode(tasksActivities.getId()+""));
            if(type.equals("1")){
                tasksActivities.setCode(getCode1(tasksActivities.getId()+""));
            }
        }

        return tasksActivitiesList;
    }

    private  String getCode(String id){
        String code="";
        for (int i=0;i<8-id.length();i++){
            code+="0";
        }
        return  code+id;
    }

    private  String getCode1(String id){
        String code="";
        for (int i=0;i<3-id.length();i++){
            code+="0";
        }
        return  code+id;
    }
    class  TaskCompare implements Comparator<TasksActivities> {
        @Override
        public int compare(TasksActivities tasksActivities, TasksActivities t1) {
            return tasksActivities.getOrder()-t1.getOrder();
        }
    }

    public AppResultData saveOrUpdate(String user,TasksActivities tasksActivities){
        if(tasksActivities.getId()==null){
            tasksActivities.setUserId(user);
            tasksActivitiesMapper.insert(tasksActivities);}
        else {
            tasksActivitiesMapper.updateByPrimaryKeySelective(tasksActivities);
        }
        return AppResultData.successMessage("成功");
    }

    public  AppResultData dianzan(CyUser cyUser,String taskId,Integer type,Integer activityId){
        String typeString="tasks";
        if((type+"").equals("1"))
            typeString="dianzan";
        AppResultData appResultData=isOver(activityId);
        if(appResultData.getStatus()!=200)
            return  appResultData;

        List<CyUser> cyUserList= cyUserMapper.findByOpenidAndTaskIdAndDaydate(cyUser.getOpenid(),taskId,new Date());
        if(cyUserList.size()>0){
            return  AppResultData.errorMessage("每天只能点赞一次");
        }
        cyUser.setId(UUID.randomUUID().toString().replaceAll("-",""));
        cyUser.setTaskId(taskId);
        cyUser.setDaydate(new Date());
        cyUser.setType(type);
        cyUserMapper.insert(cyUser);
        TasksActivities tasksActivities=new TasksActivities();
        tasksActivities.setId(Integer.parseInt(taskId));
        tasksActivitiesMapper.updateNumById(tasksActivities);
        return  AppResultData.successMessage("成功");
    }
    public  AppResultData toupiao(CyUser cyUser,String taskId){
        List<CyUser> cyUserList= cyUserMapper.findByOpenidAndTaskIdAndDaydate(cyUser.getOpenid(),taskId,new Date());
        if(cyUserList.size()>0){
            return  AppResultData.errorMessage("每天只能投票一次");
        }
        cyUser.setId(UUID.randomUUID().toString().replaceAll("-",""));
        cyUser.setTaskId(taskId);
        cyUser.setDaydate(new Date());
        cyUser.setType(1);
        cyUserMapper.insert(cyUser);
        TasksActivities tasksActivities=new TasksActivities();
        tasksActivities.setId(Integer.parseInt(taskId));
        tasksActivitiesMapper.updateNumById(tasksActivities);
        return  AppResultData.successMessage("成功");
    }
    public  AppResultData zhuli(CyUser cyUser,String openId,Integer activityId){
       AppResultData appResultData=isOver(activityId);
       if(appResultData.getStatus()!=200)
           return  appResultData;
        TasksActivities tasksActivities=tasksActivitiesMapper.findByuserIdAndtype(openId,4,activityId);
       if(tasksActivities==null){
           tasksActivities=new TasksActivities();
           tasksActivities.setType(4);
           tasksActivities.setUserId(openId);
           tasksActivities.setActivityId(activityId);
           tasksActivitiesMapper.insert(tasksActivities);
       }else {
           List<CyUser> cyUserList= cyUserMapper.findByOpenidAndTaskId(cyUser.getOpenid(),tasksActivities.getId()+"",activityId);
           if(cyUserList.size()>0){
               return  AppResultData.errorMessage("只能助力一次");
           }
       }
       if(cyUser.getOpenid().equals(openId)){
           return  AppResultData.errorMessage("不能给自己助力");
       }
        cyUser.setId(UUID.randomUUID().toString().replaceAll("-",""));
        cyUser.setTaskId(tasksActivities.getId()+"");
        cyUser.setDaydate(new Date());
        cyUser.setType(4);
        cyUser.setActivityId(activityId);
        cyUserMapper.insert(cyUser);
        //TasksActivities tasksActivities=new TasksActivities();
        tasksActivitiesMapper.updateNumById(tasksActivities);
        return  AppResultData.successMessage("成功");
    }
    public  TasksActivitiesVo findById(String openId,String id){
        TasksActivitiesVo tasksActivities=tasksActivitiesMapper.listById(openId,id).get(0);
        tasksActivities.setCode(getCode(tasksActivities.getId()+""));
        List<String> detailList=Arrays.asList(tasksActivities.getDetails().split(","));
        tasksActivities.setDetailList(detailList);
        List<String> picList=Arrays.asList(tasksActivities.getPictures().split(","));
        tasksActivities.setPicList(picList);
        List<String> videoThumbList=new ArrayList<>();
        if(tasksActivities.getHead()!=null)
        videoThumbList=Arrays.asList(tasksActivities.getHead().split(","));

        List<VideoData> videoDataList=new ArrayList<>();
        for (int i=0;i<detailList.size();i++){
            VideoData videoData=new VideoData();
            videoData.setVideo(detailList.get(i));
            if(videoThumbList.size()>0){
                videoData.setThumb(videoThumbList.get(i));
            }
            videoDataList.add(videoData);
        }
        tasksActivities.setVideoDataList(videoDataList);
        return  tasksActivities;
    }

    public  TasksActivities findId(String id){
        return  tasksActivitiesMapper.findById(id);
    }

    public  int deleteById(String id){
        return tasksActivitiesMapper.deleteById(id);
    }
   //签到
    public  AppResultData signUser(CyUser cyUser,String code,Integer activityId, HttpServletResponse httpServletResponse){
        AppResultData appResultData=isOver(activityId);
        if(appResultData.getStatus()!=200)
            return  appResultData;
        if(cyUser==null){
            cyUser=getCyUser(code,httpServletResponse);
        }
        CyUser signCyuser=cyUserMapper.findDaySign(cyUser.getOpenid(),activityId);
        if(signCyuser!=null){
            return  AppResultData.errorMessage("今日已经签到");
        }
        CyUser user=cyUserMapper.findNewSign(cyUser.getOpenid(),activityId);
        int daybet=0;
        if(user!=null){
            daybet=DateUtil.daysBetween(user.getCreateTime(),new Date());
        }
        cyUser.setType(2);
        if(daybet==1)
        cyUser.setNum(user.getNum()+1);
        else {
            cyUser.setNum(1);
        }
        cyUser.setId(UUID.randomUUID().toString().replaceAll("-",""));
        cyUser.setActivityId(activityId);
        cyUserMapper.insert(cyUser);
        return  AppResultData.successMessage("成功");
    }

    //签到排行
    public   Map<String,Object> signList(CyUser cyUser,String code,Integer activityId,HttpServletResponse httpServletResponse){
        if(cyUser==null){
            cyUser=getCyUser(code,httpServletResponse);
        }
        Map<String,Object> map=new HashMap<>();
        int signCount=cyUserMapper.findSignCount(cyUser.getOpenid(),activityId);
        map.put("count",signCount+"");
        List<CyUser> cyUserList=cyUserMapper.listSign(activityId);
        int paiming=0;
        for (int i=0;i<cyUserList.size();i++){
            if(cyUserList.get(i).getOpenid().equals(cyUser.getOpenid())){
                paiming=i+1;
            }
        }
        CyUser signCyuser=cyUserMapper.findDaySign(cyUser.getOpenid(),activityId);
        if(signCyuser==null){
            map.put("signCyuser","0");
        }else {
            map.put("signCyuser","1");
        }
        CyUser newCyuser=cyUserMapper.findNewSign(cyUser.getOpenid(),activityId);
        map.put("newCyuser",newCyuser);
        map.put("data",cyUserList);
        map.put("paiming",paiming+"");
        map.put("cyuser",cyUser);
        List<CyUser> signLists=cyUserMapper.listSigns(cyUser.getOpenid(),activityId);
        Map<String,String> signListMap=new HashMap<>();
        for (int i=0;i<signLists.size();i++){
            CyUser cyUser1=signLists.get(i);
            Calendar calendar=Calendar.getInstance();
            calendar.setTime(cyUser1.getCreateTime());
            String date=(calendar.get(Calendar.MONTH)+1)+"."+(calendar.get(Calendar.DATE));
            signListMap.put(date,"1");
        }
        Calendar cl = Calendar.getInstance();
       // Map<String,String> listMap=new HashMap<>();
        Map<String, String> listMap = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM.dd");
                        try {
                            Date date1=simpleDateFormat.parse(obj1);
                            Date date2=simpleDateFormat.parse(obj2);
                            return (int) (date1.getTime()-date2.getTime());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        return obj1.compareTo(obj2);
                    }
                });
        for (int i=0;i<7;i++){
            int month = cl.get(Calendar.MONTH)+1;
            int day = cl.get(Calendar.DATE);
            String date=month+"."+day;
            String value=signListMap.get(date);
            if(value==null){
                listMap.put(date,"0");
            }else {
                listMap.put(date,"1");
            }
            cl.set(cl.DATE,cl.get(Calendar.DATE)-1);
        }
        map.put("listMap",listMap);

        return  map;
    }

    public  int zhuliCount(CyUser cyUser,Integer type,String openId,String code,Integer activityId,HttpServletResponse httpServletResponse){
        if(cyUser==null){
            cyUser=getCyUser(code,httpServletResponse);
        }
        TasksActivities tasksActivities=tasksActivitiesMapper.findByuserIdAndtype(openId,4,activityId);
        if(tasksActivities==null){
            tasksActivities=new TasksActivities();
            tasksActivities.setType(4);
            tasksActivities.setUserId(openId);
            tasksActivities.setName(cyUser.getNickname());
            tasksActivities.setActivityId(activityId);
            tasksActivitiesMapper.insert(tasksActivities);
        }
        int zhuliCount=cyUserMapper.findCountByTypeAndTaskId(type,tasksActivities.getId()+"",activityId);
        return  zhuliCount;
    }

    public  AppResultData zhuliList(int page,Integer activityId){
        TasksActivities tasksActivities=new TasksActivities();
        tasksActivities.setType(4);
        PageHelper.startPage(page,10);
        tasksActivities.setActivityId(activityId);
        List<TasksActivities> tasksActivitiesList=tasksActivitiesMapper.lists(tasksActivities);
        PageInfo pageInfo=new PageInfo(tasksActivitiesList);
        return  AppResultData.success(pageInfo.getTotal()+"",pageInfo.getList());
    }

//    class  MapCompare implements Comparator<Map<String,String>> {
//        @Override
//        public int compare(Map<String,String> map, Map<String,String> map1) {
//            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM.dd");
//
//            return tasksActivities.getOrder()-t1.getOrder();
//        }
//    }
    private  CyUser getCyUser(String code,HttpServletResponse httpServletResponse){
        String uuid=UUID.randomUUID().toString().replaceAll("-","");
        String userString="{\"openid\":\"o9XqEwoibgA2_D3fLBVQ7LV6h8u\",\"nickname\":\"呲尔不登睬等彩\",\"sex\":1,\"language\":\"zh_CN\",\"city\":\"太原\",\"province\":\"山西\",\"country\":\"中国\",\"headimgurl\":\"http:\\/\\/thirdwx.qlogo.cn\\/mmopen\\/vi_32\\/Q0j4TwGTfTKnibcf171MCFsR7JaYibBElK8wrol4ebFibrZWECZaRh81Eq8Ds8X3pMxY1U7OQsjsxN4yvDiaEVhTZg\\/132\",\"privilege\":[]}";
       // String userString=OkhttpUtil.getInstance().getWeixinAccess(code);
        if(!UserConfigUtil.isDebug)
            userString=OkhttpUtil.getInstance().getWeixinAccess(code);
        userString= userString.replaceAll("\\[","\"");
        userString=userString.replaceAll("]","\"");
        redisDao.putSecondValue(uuid,userString,30*60*1000);
        Cookie cookie=new Cookie("user",uuid);
        cookie.setMaxAge(30*60*1000);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
        return  CommGson.getInstance().toObject(userString,CyUser.class);
    }


    public  AppResultData listSigns(int page,Integer activityId){
        PageHelper.startPage(page,10);
        List<CyUser> cyUserList=cyUserMapper.listSign(activityId);
        PageInfo pageInfo=new PageInfo(cyUserList);
        List<CyUser> userList=pageInfo.getList();
        List<SignVo> signVoList=new ArrayList<>();
        for (int i=0;i<userList.size();i++){
            CyUser cyUser=cyUserList.get(i);
            SignVo signVo=new SignVo();
            signVo.setNum(cyUser.getNum());
            signVo.setCreateTime(cyUser.getCreateTime());
            signVo.setNickname(cyUser.getNickname());
            signVo.setPaiming(i+1);
            signVo.setOpenid(cyUser.getOpenid());
            signVoList.add(signVo);
        }
        return  AppResultData.success(pageInfo.getTotal()+"",signVoList);
    }

    public  AppResultData listZhuli(int page,String taskId){
        PageHelper.startPage(page,10);
        List<CyUser> cyUserList=cyUserMapper.findByTaskId(taskId);
        PageInfo pageInfo=new PageInfo(cyUserList);
        return  AppResultData.success(pageInfo.getTotal()+"",pageInfo.getList());
    }
   public  AppResultData listUserSign(String openid,Integer activityId,int page){

       PageHelper.startPage(page,10);
       List<CyUser> cyUserList=cyUserMapper.listUserSign(openid,activityId);
       PageInfo pageInfo=new PageInfo(cyUserList);

        return  AppResultData.success(pageInfo.getTotal()+"",pageInfo.getList());
    }
    public  AppResultData saveDate(String type,String startDate,String endDate){
         redisDao.putForeverValue(type+"startDate",startDate);
        redisDao.putForeverValue(type+"endDate",endDate);
        return  AppResultData.successMessage("成功");
    }
    public  AppResultData saveZhuli(String title,String content){
        redisDao.putForeverValue("title",title);
        redisDao.putForeverValue("content",content);
        return  AppResultData.successMessage("成功");
    }
    public  AppResultData getZhuli(Integer activityId){
        String title=redisDao.getValue("title");
        String content=redisDao.getValue("content");
        Map<String,String> map=new HashMap<>();
        map.put("title",title);
        map.put("content",content);
        return  AppResultData.success("成功",map);
    }

    public  Map<String,String> getZhuliMap(){
        String title=redisDao.getValue("title");
        String content=redisDao.getValue("content");
        Map<String,String> map=new HashMap<>();
        map.put("title",title);
        map.put("content",content);
        return  map;
    }
    public  AppResultData getDates(String type){
        Map<String,String> map=new HashMap<>();
        String startDate=redisDao.getValue(type+"startDate");
        String endDate=redisDao.getValue(type+"endDate");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String nowDate=simpleDateFormat.format(new Date());
        if(startDate==null){
            redisDao.putForeverValue(type+"startDate",nowDate);
            startDate=nowDate;
        }
        if(endDate==null){
            redisDao.putForeverValue(type+"endDate",nowDate);
            endDate=nowDate;
        }
        map.put("endDate",endDate);
        map.put("startDate",startDate);
        return  AppResultData.success("成功",map);
    }

    public   AppResultData isOver(Integer activityId){
        Activitys activitys=activitysMapper.selectByPrimaryKey(activityId);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
       // String realStartDateString=redisDao.getValue(type+"startDate");
        try {
            Date realStartDate=activitys.getStartDate();
            Date startDateDate=new Date();
            if(startDateDate.getTime()<realStartDate.getTime()){
                return  AppResultData.errorMessage("活动开始时间为"+simpleDateFormat.format(realStartDate));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
       // String realEndDateString=activitys.getEndDate();
        try {
            Date realEndDate=activitys.getEndDate();
            Date endDateDate=new Date();
            if((realEndDate.getTime()+1)<endDateDate.getTime()){
                return  AppResultData.errorMessage("活动结束时间为"+simpleDateFormat.format(realEndDate));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  AppResultData.successMessage("成功");
    }

    //获取后台宣传活动内容
     public  XuanChuanBean  getHtXuan(){
        String xuanString=redisDao.getValue("xuan");
         XuanChuanBean xuanChuanBean=new XuanChuanBean();
        if(xuanString!=null){
            xuanChuanBean=CommGson.getInstance().toObject(xuanString,XuanChuanBean.class);
        }
        return  xuanChuanBean;
     }

    //获取后台宣传活动内容
    public  AppResultData  saveHtXuan(XuanChuanBean xuanChuanBean){
       redisDao.putForeverValue("xuan",CommGson.getInstance().toString(xuanChuanBean));
        return  AppResultData.successMessage("成功");
    }

    public  AppResultData addZhuanfa(Integer activityId){
        String share=redisDao.getValue("share"+activityId);
        if(share==null){
            share="0";
        }else {
            share=(Integer.parseInt(share)+1)+"";
        }
        redisDao.putForeverValue("share"+activityId,share);
        return  AppResultData.success("成功",share);
    }
}
